<?php
include_once 'Conexao.php';

class RepositorioNoticias{
	private static $instancia;
	
	private function __construct(){	
	}
	
	private function __destruct(){
	}
	
	
	public static function getInstancia(){
		if(!isset(self::$instancia)){
			$c = __CLASS__;
			self::$instancia = new $c;
		}
		return self::$instancia;
	}
	
	public static function adicionaNoticia(Noticias $noticia){
		__autoload("NoticiasCadastraException");
		try{
			if(isset($noticia)){
				$data = self::converteData($noticia->getData());
				
				$sql = "INSERT INTO `noticias`(`n_data`, `n_titulo`, `n_texto`)
					VALUES ('";
				$sql = $sql.$data."','";
				$sql = $sql.$noticia->getTitulo()."','";
				$sql = $sql.$noticia->getTexto();
				$sql = $sql."')";
				

				Conexao::executaSql($sql);
			}	
		}
		catch (NoticiasCadastraException $e){
			echo $e->getMessage();
		}
	}
	
	public static function visualizaNoticias(){
		$sql = "SELECT * FROM `noticias` ORDER BY `n_id` DESC;";
		
		$tabela = Conexao::tabelaSql($sql);
		
		return $tabela;
	}
	
	
	private static function converteData($data){
		if(!is_null($data)){
				
			$dataTab = array();
			$dataTab = split("/", $data);
				
			$data = "";
			for($i=count($dataTab)-1; $i>=0; $i--){
				$data .= $dataTab[$i];
				$data .="-";
			}
			$data =substr($data, 0, -1);
				
			return $data;
		}
		else{
			__autoload("DataException");
			$e = new DataException();
			echo $e->getMessage();
		}
	}
}
?>